package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import entity.UserAddress;

public class UserAddressDao extends BaseDao{
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;

	public List<UserAddress>  findByUserId(int userId) {
		List<UserAddress> list = new ArrayList<>();
		try {
			conn = super.getConnection();
			
			//查询内容数据
			String sql = "select id,userId,address,createTime,isDefault,remark from easybuy_user_address where userId=? ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setObject(1, userId);
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				UserAddress userAddress = new UserAddress();
		        userAddress.setId(rs.getInt("id"));
		        userAddress.setAddress(rs.getString("address"));
		        userAddress.setUserId(rs.getInt("userId"));
		        userAddress.setCreateTime(rs.getString("createTime"));
		        userAddress.setRemark(rs.getString("remark"));
		        
		        list.add(userAddress);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
        	super.closeAll(conn, pstmt, rs);
        }
		return list;
	}
	public int addUserAddress(int userId, String newAddress, String newRemark) {
		int id = -1;
		
		String sql=" INSERT into easybuy_user_address(userId,address,createTime,isDefault,remark) VALUES(?,?,?,?,?) ";
        try {
        	conn = super.getConnection();
        	pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
    		
    		pstmt.setObject(1, userId);
    		pstmt.setObject(2, newAddress);
    		pstmt.setObject(3, new Date());
    		pstmt.setObject(4, 0);
    		pstmt.setObject(5, newRemark);
    		
    		pstmt.executeUpdate();
    		
    		ResultSet rs = pstmt.getGeneratedKeys(); 
			if (rs.next()) { 
				id = rs.getInt(1);
				System.out.println("数据主键：" + id); 
			} 
    		
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	super.closeAll(conn, pstmt, rs);
        }
		return id;
	}

	public UserAddress findById(int id) {
		
		UserAddress userAddress = null;
		try {
			conn = super.getConnection();
			
			//查询内容数据
			String sql = "select id,userId,address,createTime,isDefault,remark from easybuy_user_address where id=? ";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setObject(1, id);
			rs = pstmt.executeQuery();
			
			while (rs.next()) {
				userAddress = new UserAddress();
		        userAddress.setId(rs.getInt("id"));
		        userAddress.setAddress(rs.getString("address"));
		        userAddress.setUserId(rs.getInt("userId"));
		        userAddress.setCreateTime(rs.getString("createTime"));
		        userAddress.setRemark(rs.getString("remark"));
		        
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
        	super.closeAll(conn, pstmt, rs);
        }
		return userAddress;
	}

}
